/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mdp.oauth2.client.user.ctrl;

import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.safe.client.entity.CommonUserDetails;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.jwt.JwtLocalLoginService;
import com.mdp.safe.client.utils.LoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.MapOAuth2AccessTokenResponseConverter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.reactive.function.client.WebClient;

import javax.servlet.http.HttpServletRequest;

import java.nio.charset.Charset;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Joe Grandja
 * @since 0.0.1
 */

@Controller
public class AuthorizationCodeController {

	@Autowired
	JwtLocalLoginService jwtLoginService;

	@Autowired
	ClientRegistrationRepository clientRegistrationRepository;

	MapOAuth2AccessTokenResponseConverter converter=new MapOAuth2AccessTokenResponseConverter();




	@GetMapping(value = "/authorize", params = "grantType=authorization_code")
	public String authorizationCodeGrant(Model model,
			@RegisteredOAuth2AuthorizedClient("code-client")
					OAuth2AuthorizedClient authorizedClient) {

		model.addAttribute("data", "获取到 token = "+authorizedClient.getAccessToken().getTokenValue());

		return "index";
	}

	// '/authorized' is the registered 'redirect_uri' for authorization_code
	@GetMapping(value = "/authorized", params = OAuth2ParameterNames.ERROR)
	public String authorizationFailed(Model model, HttpServletRequest request) {
		String errorCode = request.getParameter(OAuth2ParameterNames.ERROR);
		if (StringUtils.hasText(errorCode)) {
			model.addAttribute("data",
					new OAuth2Error(
							errorCode,
							request.getParameter(OAuth2ParameterNames.ERROR_DESCRIPTION),
							request.getParameter(OAuth2ParameterNames.ERROR_URI))
			);
		}

		return "index";
	}
	@GetMapping(value = "/authorized", params = {OAuth2ParameterNames.CODE})
	public String authorizationSuccess(Model model, HttpServletRequest request  ) {
		String code = request.getParameter(OAuth2ParameterNames.CODE);
		ClientRegistration client=clientRegistrationRepository.findByRegistrationId("code-client");
		Map<String,Object> params=new HashMap<>();
		//params.put("username","vybe8882");
		//params.put("password","vybe8882");
		//params.put("clientId",client.getClientId());
		params.put("redirectUri",client.getRedirectUri());
		params.put("code",code);
		params.put("grantType",client.getAuthorizationGrantType().getValue());
		Map messages = WebClient.create()
				.post()
				.uri(client.getProviderDetails().getTokenUri()+"?grant_type={grantType}&code={code}&redirect_uri={redirectUri}",params)
				.headers(h->{
					h.add("Authorization","Basic "+ Base64.getEncoder().encodeToString((client.getClientId()+":"+client.getClientSecret()).getBytes(Charset.forName("UTF-8"))));
				})
				.retrieve()
				.bodyToMono(Map.class)
				.block();
		Tips tips = new Tips("成功");
		OAuth2AccessTokenResponse response=converter.convert(messages);
		Result result= Result.ok().setData(response).setTips(LangTips.fromTips(tips));
		String accessToken= response.getAccessToken().getTokenValue();
		jwtLoginService.doLocalLoginUseJwtToken(accessToken);
		User user= LoginUtils.getCurrentUserInfo();
		result.put("userInfo",user);
		CommonUserDetails userDetails=jwtLoginService.getUserDetails();
		result.put("roles",userDetails.getAuthorities());
		model.addAllAttributes(result);
		return "index";
	}
}
